import config from './config.js' 
import http from './http.js'
import mockData from './mockData.js'
import microphoneUtil from './microphoneUtil' 

var sysCfg = null 

function saveCache(key, vals) {
  try {
    uni.setStorageSync(key, vals)
  } catch (e) {
    console.log(e)
  }
}

function getCache(key, def) {
  try {
    var value = uni.getStorageSync(key) 
    return value || def;
  } catch (e) {
    return def;
  }
}

var blocks = {} 
// 设置处于堵塞中 ，duration: 毫秒 
function setInBlock(key, duration = 300) { 
  blocks[key] = Date.now() + duration 
} 

function isInBlock(key) { 
  if (blocks[key] && Date.now() < blocks[key]) { 
    console.log('=== in block: ' + key) 
    return true 
  }
  return false 
} 

function strToJson(str, def) {
  if (typeof(str) == 'string' && str.length > 0) {
    try {
      return JSON.parse(str);
    } catch(e) {
      console.log(e);
    }
  } 
    return def;
}

var timerShow = null
var timerHide = null
var isLoadingShow = false 

// 显示loading框, 举例：utils.showLoading('加载中', true, 1000, 5000) 
function showLoading(tips, isMask, delay, duration) { 
  hideLoading()
  const self = this 
  const doShow = function() { 
    isLoadingShow = true 
    uni.showLoading({
      title: tips, 
      mask: isMask 
    })
    if (typeof(duration) == 'number') { 
      timerHide = setTimeout(function(){
        timerHide = null 
        hideLoading() 
      }, duration) 
    }
  }
  
  if (typeof(delay) == 'number') {
    timerShow = setTimeout(function() {
      timerShow = null 
      doShow()
    }, delay) 
  } else {
    doShow() 
  } 
}

function hideLoading() { 
  if (timerShow != null) {
    clearTimeout(timerShow) 
    timerShow = null 
  }
  if (timerHide != null) {
    clearTimeout(timerHide) 
    timerHide = null 
  }
  if (isLoadingShow) {
    uni.hideLoading() 
    isLoadingShow = false 
  }
} 

function getVideolist(autoErrToast=true) {
  return new Promise( (resolve)=>{
    if (config.isLocalMock) {
      return resolve(mockData.getVideolist()) 
    } else {
      showLoading('努力加载中...', true, 500, 5000) 
      http.post('api/video/list', {}).then((data)=> { 
        hideLoading() 
        if (data) { 
          resolve(data) 
        } else {  
          resolve([]) 
        } 
      }) 
      .catch((err)=>{ 
        hideLoading() 
        resolve([]) 
      }) 
    }
  })
}

function getSysConfig() {
  return new Promise(resolve=>{
    if (sysCfg) {
      resolve(sysCfg) 
    } else {
      http.post('api/config/info', {}).then((data)=> {
        sysCfg = data 
        resolve(data) 
      }) 
      .catch((err)=>{ 
        resolve(null) 
      })
    }
  })
}

// 定时任务上传录制的视频文件
var scheduleTimerId = null 
function startVideoUploadSchedule() {
  console.log('启动定时任务(上传录制的视频)...')
  
  const scheduleTask = function() {
    stopVideoUploadSchedule() 
    
    getSysConfig().then(data=>{ 
      const [hours, minutes, seconds] = data.upload_time.split(':').map(Number) 
      const targetTime = new Date() 
      targetTime.setHours(hours, minutes, seconds, 0) 
      let deltaTime = targetTime.getTime() - Date.now() 

      // 如果现在时间已经过了6点，就设置到明天6点 
      if (deltaTime < 0) { 
        targetTime.setDate(targetTime.getDate() + 1) 
        deltaTime = targetTime.getTime() - Date.now() 
      } 
      console.log(`定时任务距离执行还有: ${Math.round(deltaTime/1000)} 秒`);
      
      scheduleTimerId = setTimeout(() => { 
        console.log('执行定时任务: 上传录制的视频文件') 
        scheduleTimerId = null 
        window.api?.startUploadRecordVideos() 
        
        // 设置下一次执行（24小时后）
        scheduleTask() 
      }, deltaTime) 
      
    })
    .catch(()=>{
      // 半小时候再尝试 
      console.log('定时任务启动失败, 半小时后重试') 
      scheduleTimerId = setTimeout(scheduleTask, 30*60*1000)
    })
  }
  
  // 启动定时任务
  scheduleTask() 
}

// 提供停止函数
function stopVideoUploadSchedule() {
  if (scheduleTimerId) {
    clearTimeout(scheduleTimerId)
    scheduleTimerId = null
    console.log('视频上传定时任务已停止')
  }
}

module.exports = {
  saveCache,
  getCache,
  setInBlock,
  isInBlock,
  strToJson,
  showLoading,
  hideLoading,
  getVideolist,
  getSysConfig,
  startVideoUploadSchedule,
  stopVideoUploadSchedule,
}